package com.z;

import java.util.List;
import java.util.Queue;

public class Parser {

    Queue<String> instructions;
    final String rePush = "";
    final String rePop = " ";
    CodeWriter codeWriter;
    String fileName;


    public Parser(Queue<String> instructions,String fileName) {
        this.instructions = instructions;
        this.codeWriter = new CodeWriter();
        this.fileName = fileName;

    }

    public String processFile() {
        String output = "";

        while (hasMoreCommands()) {
            String poll = instructions.poll();
            if (isValidCommand(poll)) {

                output += advance(poll, fileName);

            }
        }

        return output;
    }

    String advance(String command, String fileName) {
        String output = "";
        String commandType = commandType(command);

        switch (commandType) {
            case "push":
            case "pop":
                output = codeWriter.writePushPop(command, commandType, fileName);   // 需要fileName是因为对static操作需要fileName;
                break;
            case "arith":
                output = codeWriter.writeArithmetic(command);

        }

        return output;

    }

    // 判断命令的类型
    String commandType(String command) {
        if (command.startsWith("push")) {
            return "push";
        } else if (command.startsWith("pop")) {
            return "pop";
        } else {

            return "arith";
        }
    }

    // 判断命令是否有效
    // 注释和空即为无效
    boolean isValidCommand(String command) {
        if (command == "" || command.startsWith("//")) {
            return false;
        } else {
            return true;
        }

    }


    public boolean hasMoreCommands() {
        return instructions.size() > 0;
    }


}
